<template>
  <section class="home-container">
    <Master title="权限菜单管理">
      <div slot="searchContent" class="search-content-slot">
        <Form :model="searchs" :label-width="100">
          <Row>
            <Col span="10" v-can:SearchMenu>
              <FormItem label="名称：">
                <Input
                  style="width: 50%"
                  :maxlength="20"
                  v-model="searchs.Condition.Name"
                  placeholder="输入名称"
                ></Input>
              </FormItem>
            </Col>

            <Col span="10" v-can:SearchMenu>
              <FormItem label="编码：">
                <Input
                  style="width: 50%"
                  v-model="searchs.Condition.Code"
                  :maxlength="18"
                  placeholder="输入编码"
                ></Input>
              </FormItem>
            </Col>
            <Col span="4" pull="4"
              >&nbsp;&nbsp;<Button
                v-can:SearchMenu
                type="info"
                icon="ios-search"
                @click="searchByCondition"
                :loading="searching"
                >查询</Button
              >
              &nbsp;
              <Button
                v-can:AddMenu
                type="primary"
                icon="md-add"
                @click="
                  formData = {};
                  addModalVisible = true;
                  showAdd();
                "
                >添加</Button
              >
            </Col>
          </Row>
        </Form>
      </div>
      <div slot="paddingContent" v-can:SearchMenu>
        <Table :columns="columns" :data="list">
          <!-- 状态 -->
          <template v-slot:state="{ row: { Enabled } }">
            {{ Enabled ? "禁用" : "启用" }}
          </template>
          <!-- 操作 -->
          <template v-slot:action="{ row }">
            <Button
              v-can:EditMenu
              type="primary"
              size="small"
              @click="
                formData = { ...row };
                editModalVisible = true;
              "
              >编辑</Button
            >
            <Button
              v-can:DeleteMenu
              type="error"
              size="small"
              class="lr5"
              :loading="deleting"
              @click="remove(row)"
              >删除</Button
            >
          </template>
        </Table>
      </div>
      <div slot="pager" v-can:SearchMenu>
        <MyPage v-model="searchs" @change="selectCondition"></MyPage>
      </div>
    </Master>
    <!-- 修改医生 -->
    <Modal v-model="editModalVisible" title="修改医生" v-can:EditMenu>
      <Form
        :model="formData"
        :label-width="80"
        ref="formEdit"
        :rules="ruleInline"
      >
        <FormItem label="真实名称" prop="RealName">
          <Input
            v-model="formData.RealName"
            :maxlength="20"
            placeholder="输入用户真实名称"
          ></Input>
        </FormItem>
        <FormItem label="密码">
          <Input
            v-model="formData.Password"
            :maxlength="20"
            type="password"
            placeholder="为空则不修改密码"
          ></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="editModalVisible = false">关闭</Button>
        <Button type="primary" @click="editDcotor" :loading="saving"
          >保存</Button
        >
      </div>
    </Modal>
    <Modal title="添加权限" v-can:AddMenu v-model="addModalVisible">
      <Form
        :model="formData"
        :label-width="80"
        ref="formData"
        :rules="ruleInline"
      >
        <FormItem label="名称" prop="Name">
          <Input
            v-model="formData.Name"
            :maxlength="20"
            placeholder="输入名称"
          ></Input>
        </FormItem>
        <FormItem label="编码" prop="Code">
          <Input
            v-model="formData.Code"
            :maxlength="20"
            placeholder="输入编码"
          ></Input>
        </FormItem>
        <FormItem label="排序号" prop="Order">
          <Input
            v-model="formData.Order"
            :maxlength="20"
            placeholder="输入排序号"
          ></Input>
        </FormItem>
        <FormItem label="是否显示" prop="Password">
          <Select v-model="formData.Display" placeholder="请选择">
            <Option value="true">显示</Option>
            <Option value="false">不显示</Option>
          </Select>
        </FormItem>
        <FormItem label="父Id" prop="ParentId">
          <Select v-model="formData.ParentId">
            <Option v-for="item in menus" :value="item.Id" :key="item.Id">{{
              item.Name
            }}</Option>
          </Select>
        </FormItem>
        <br />
        <br />
        <br />
        <br />
      </Form>
      <div slot="footer">
        <Button @click="addModalVisible = false">关闭</Button>
        <Button type="primary" @click="register" :loading="saving">保存</Button>
      </div>
    </Modal>
  </section>
</template>
<script>
import { GetAll, GetAlls, AddMenu, Delete } from "@/api/Menu.js";
import { mapState } from "vuex";

export default {
  data() {
    return {
      /**
       * 是否保存中
       */
      saving: false,
      /**
       * 获取角色中
       */
      gettingRoles: false,
      /**
       * 角色ID
       */
      roleId: 0,
      /**
       * 添加对话框的属性
       */
      addModalVisible: false,
      /**
       * 表单数据
       */
      formData: {
        Name: "",
        Code: "",
        Display: "true",
        ParentId: 0,
        Order: 0,
      },
      /**
       * 所有权限
       */
      menus: [],
      /**
       * 修改对话框的属性
       */
      editModalVisible: false,
      /**
       * 分配角色模态框
       */
      assignVisible: false,
      /**
       * 表格列
       */
      columns: [
        {
          title: "名称",
          align: "center",
          key: "Name",
        },
        {
          title: "编码",
          align: "center",
          key: "Code",
        },
        {
          title: "状态",
          align: "center",
          key: "Display",
          slot: "state",
        },
        {
          title: "操作",
          width: 240,
          align: "center",
          slot: "action",
        },
      ],
      /**
       * 表单规则
       */
      ruleInline: {
        Name: [
          {
            required: true,
            message: "名称不能为空",
            trigger: "blur",
          },
          {
            type: "string",
            min: 2,
            max: 20,
            message: "名称必须为2-20位",
            trigger: "blur",
          },
        ],
        Code: [
          {
            required: true,
            message: "编码不能为空",
            trigger: "blur",
          },
          {
            type: "string",
            min: 2,
            max: 20,
            message: "编码必须为2-20位",
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {
    ...mapState(["user"]),
  },
  methods: {
    /**
     * 编辑医生
     */
    async editDcotor() {
      try {
        const result = await this.$refs.formEdit.validate();
        if (!result) {
          return;
        }
        this.saving = true;
        await Update(this.formData);
        this.$Message.success("修改成功");
        this.editModalVisible = false;
        this.selectCondition();
      } catch (e) {}
      this.saving = false;
    },
    /**
     * 删除
     */
    async remove(row) {
      try {
        await this.$confirm(`您确定要删除【${row.Name}】吗？`);
        this.deleting = true;
        if (await Delete(row.Id)) {
          this.selectCondition();
          this.$Message.success("删除成功！");
        } else {
          this.$Message.error("删除失败，请稍后再试");
        }
      } catch (error) {
        console.log(error);
      }
      this.deleting = false;
    },
    /**
     * 插入新权限
     */
    async register() {
      try {
        const result = await this.$refs.formData.validate();
        if (!result) {
          return;
        }
        this.saving = true;
        await AddMenu(this.formData);
        this.$Message.success("添加成功！");
        this.addModalVisible = false;
        this.selectCondition();
      } catch (error) {}
      this.saving = false;
    },
    async showAdd() {
      this.menus = await GetAlls();
    },
    /**
     * 查询
     */
    async selectCondition() {
      if (!this.$validR("SearchMenu")) {
        return;
      }
      try {
        this.searching = true;
        const { Result, Total } = await GetAll(this.searchs);
        this.list = Result;
        this.searchs.total = Total;
      } catch (error) {}
      this.searching = false;
    },
    /**
     * 打开分配权限页面
     */
    async assignRole() {
      this.gettingRoles = true;
      await this.getAllRoles();
      this.gettingRoles = false;
      this.assignVisible = true;
      this.roleId = this.formData.RoleId;
    },
    /**
     * 提交分配角色
     */
    async confirmAssignRole() {
      try {
        if (!this.roleId || this.roleId < 1) {
          return this.$Message.warning("请选择角色");
        }
        const self =
          this.user.Id === this.formData.Id && this.user.RoleId !== this.roleId;
        if (self) {
          await this.$confirm(
            "您确定要修改当前登录人的角色吗？如果修改的话则会重新登录"
          );
        }
        this.saving = true;
        const result = await UpdateRole({
          Id: this.formData.Id,
          RoleId: this.roleId,
        });
        if (!result) {
          return this.$Message.warning("角色更新失败，请稍后再试");
        }
        this.$Message.success("角色更新成功");
        if (self) {
          return this.$exit();
        }
        this.assignVisible = false;
        this.selectCondition();
      } catch (error) {
        console.log(error);
      } finally {
        this.saving = false;
      }
    },
  },
  created() {
    this.selectCondition();
  },
};
</script>

<style lang="postcss" scoped>
/deep/.ivu-form-item .ivu-select-dropdown-list {
  max-height: 80px;
  overflow-y: auto;
}

.search-title {
  padding: 0 5px 0 1px;
}
</style>